package com.webinsky.web.freemarker;

import com.webinsky.web.freemarker.model.StaticModel;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;

public abstract class StaticFreemarker {

    protected Configuration cfg;

    protected StaticModel model;

    public StaticFreemarker(Configuration cfg) {
        this.cfg = cfg;
    }

    public void setModel(StaticModel model) {
        this.model = model;
    }

    public abstract void outputFile(File file) throws IOException, TemplateException;
    public void outputFile(String... paths) throws IOException, TemplateException {
        AtomicReference<File> path = new AtomicReference<>();
        Arrays.stream(paths).forEach(p -> {
            if (p != null) {
                if (path.get() == null) {
                    path.set(new File(p));
                } else {
                    path.set(new File(path.get(), p));
                }
            }
        });
        File parent = path.get().getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        outputFile(path.get());
    }
}
